package com.testdocs.client.test.group.add;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.testdocs.client.common.i18n.CommonConstants;
import com.testdocs.client.test.i18n.TestConstants;
import com.testdocs.client.validation.ConstraintViolationException;
import com.testdocs.client.validation.FieldConstraint;
import com.testdocs.client.validation.ValidationConstraint;

public class NewTestGroupDialog {
	private static NewTestGroupDialogUiBinder uiBinder = GWT
			.create(NewTestGroupDialogUiBinder.class);

	@UiTemplate("NewTestGroupDialog.ui.xml")
	interface NewTestGroupDialogUiBinder extends
			UiBinder<Widget, NewTestGroupDialog> {
	}

	ActionConfirmedHandler handler;

	@UiField
	DialogBox dialogBox;
	@UiField
	Label nameLabel;
	@UiField
	TextBox nameTextBox;

	@UiField
	Label nameErrorLabel;

	@UiField
	Button okButton;
	@UiField
	Button cancelButton;

	private TestConstants testConstants = (TestConstants) GWT
			.create(TestConstants.class);
	private CommonConstants commonConstants = (CommonConstants) GWT
			.create(CommonConstants.class);

	public NewTestGroupDialog(ActionConfirmedHandler handler) {
		this.handler = handler;
		uiBinder.createAndBindUi(this);
		dialogBox.setText(testConstants.createTestGroup());
		nameLabel.setText(testConstants.groupName());
		okButton.setText(commonConstants.ok());
		cancelButton.setText(commonConstants.cancel());
	}

	@UiHandler("cancelButton")
	void handleCancel(ClickEvent e) {
		hide();
	}

	@UiHandler("okButton")
	void handleOk(ClickEvent e) {
		clearErrors();
		try {
			handler.handle(nameTextBox.getText());
			hide();
		} catch (ConstraintViolationException exception) {
			for (ValidationConstraint constraint : exception
					.getValidationConstraints()) {
				if (constraint instanceof FieldConstraint
						&& ((FieldConstraint) constraint).getField().equals(
								"name")) {
					nameErrorLabel.setText(constraint.getMessage());
				}
			}
		}
	}

	public void show() {
		dialogBox.center();
		dialogBox.show();
		nameTextBox.setFocus(true);
		nameTextBox.setText("");
		clearErrors();
	}

	public void hide() {
		dialogBox.hide();
	}

	private void clearErrors() {
		nameErrorLabel.setText("");
	}

	public interface ActionConfirmedHandler extends EventHandler {
		public void handle(String name)
				throws ConstraintViolationException;
	}
}
